package com.bupt.ilink.controller.LearningPlaza.File;

import com.bupt.ilink.entity.Studyspace.StudyFileSource;
import com.bupt.ilink.mapper.FileContentMapper;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.bupt.ilink.service.File.FileResponseService;
import com.bupt.ilink.service.File.FileUploadService;
import com.bupt.ilink.utils.R;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.io.BufferedInputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;
import java.io.IOException;

@Slf4j
@RestController
public class FileHandleController {

    @Autowired
    private FileUploadService fileUploadService;

    @Autowired
    private FileResponseService fileResponseService;

    @Autowired
    private FileContentMapper fileContentMapper;

//    private String tempFilePath = "tempFile.tmp";

    // 下载远程文件并保存为本地文件
    public static void downloadFile1(String downloadUrl, String path) {
        try (InputStream inputStream = new BufferedInputStream(new URL(downloadUrl).openStream());
             OutputStream outputStream = new FileOutputStream(path)) {

            byte[] buffer = new byte[1024 * 1024 * 5]; // 5MB buffer
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/uploadFileFromUrl")
    public R uploadFileFromUrl(@RequestParam("url") String fileUrl, @RequestParam("filesourceId") Long filesourceId) {
        String apiKey = "sk-36ef0e3632a545c38af1c48164b19769";  // 这里替换为你的实际API Key
        // 使用唯一标识符为每个请求生成唯一的临时文件名,避免并发冲突
        String tempFilePath = "tempFile_tingwu" + filesourceId + ".tmp";

        try {
            // 下载文件
            downloadFile1(fileUrl, tempFilePath);
            File file = new File(tempFilePath);

            // 获取 tongyiId
            String tongyiId = fileUploadService.id_return(file, apiKey);

            // 调用 fileResponseService 处理文件
            fileResponseService.generateCompletion(tongyiId, apiKey);

            // 获取处理后的内容
            Map<String, JsonNode> contentMap = fileResponseService.getContent(tongyiId);

            // 检查 contentMap 中的值是否为 null，如果为 null 则赋予空字符串
            String introduction = contentMap.get("introduction") != null ? contentMap.get("introduction").toString() : "";
            String mindmap = contentMap.get("mindmap") != null ? contentMap.get("mindmap").toString() : "";

            // 将处理后的内容插入或更新数据库
            if (!fileContentMapper.updateFileContent(introduction, mindmap, tongyiId, filesourceId)) {
                return R.failure("数据库上传失败");
            }

            // 返回成功响应
            return R.ok("文件上传并处理成功", tongyiId);

        } catch (Exception e) {
//            e.printStackTrace();
            log.error("百炼上传文件时出现错误："+e.getMessage());
            return R.failure("文件上传或处理失败: " + e.getMessage());
        }finally {
            // 在文件使用完毕后，删除临时文件
            File tempFile = new File(tempFilePath);
            if (tempFile.exists()) {
                boolean deleted=tempFile.delete();
                if (!deleted) {
                    log.error("删除临时文件失败:"+tempFile);
                }
            }
        }
    }

    @GetMapping("/filecontent")
    public R getFileContentByPage(@RequestParam Long filesource_id) {
        try {
            // 获取文件的内容
            //Map<String, JsonNode> fileContent = fileResponseService.getContent(tongyiId);
            StudyFileSource.FileContentDTO  fileContent1 = fileContentMapper.selectIntroductionTranslationMindmapByFileSourceId(filesource_id);
            System.out.println("文件内容"+fileContent1);

            return R.ok("文件内容", fileContent1);
        } catch (Exception e) {
            return R.failure("读取文件内容失败: " + e.getMessage());
        }
    }

    private String readPDFPage(String filePath, int pageNumber) throws IOException {
        PdfReader reader = null;

        try {
            reader = new PdfReader(filePath);
            if (pageNumber > reader.getNumberOfPages() || pageNumber < 1) {
                throw new IllegalArgumentException("页码超出范围");
            }
            return PdfTextExtractor.getTextFromPage(reader, pageNumber);
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
    }
}
